<template>
  <!-- <p @click.stop="handleRemoveFormDataItem">{{id}}</p> -->
  <Collapsible v-model:open="isOpen" class="relative rounded-md bg-muted p-4">
    <collapsible-trigger as-child>
      <div class="flex w-full items-center justify-between">
        <div class="flex items-center gap-x-2">
          <component :is="isOpen ? 'ChevronDown' : 'ChevronUp'" class="h-4 w-4 cursor-pointer" />
          <p class="text-xs">{{ priorityIndex ? '否则如果' : '如果' }}</p>
          <div v-if="DLSData.data.branchs.length > 1" class="font-xs rounded-md bg-gray-200 p-1 text-xs">
            优先级 <span>{{ getIndex + 1 }}</span>
          </div>
        </div>
        <component
          :is="properties.json.icon"
          :size="properties.json.size"
          :color="DLSData.data.branchs.length == 1 ? properties.json.color : 'rgb(139 139 149)'"
          @click.stop="handleRemoveFormDataItem"
        />
      </div>
    </collapsible-trigger>
    <collapsible-content class="flex items-center">
      <div class="flex w-[34px] flex-col self-stretch pb-12 pt-11 text-gray-400" v-if="conditions.length > 1">
        <div class="if-left-top-line basis-1/3">
          <div class="line"></div>
        </div>
        <div class="flex items-center text-xs text-primary">
          <Select class="border-0 bg-muted" defaultValue="and" v-model:model-value="ItemInfo.logical">
            <SelectTrigger class="andStyle! text-primary-400 w-full text-xs" as="div">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectGroup>
                <SelectItem value="and"> 且 </SelectItem>
                <SelectItem value="or"> 或 </SelectItem>
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
        <div class="if-left-bottom-line basis-1/3">
          <div class="line"></div>
        </div>
      </div>
      <div class="formBox ifNodeStyle mt-2 flex-1">
        <div class="align-center grid grid-cols-[100px_100px_1fr] gap-x-3">
          <Label :key="index" v-for="(item, index) in labels"> {{ item.label }} </Label>
        </div>
        <div class="mt-2 flex flex-wrap items-center gap-x-2 gap-y-2">
          <div v-for="(item, index) in branchList" :key="index" :class="item.class">
            <!-- {label:item.modelValue,value:item.modelValue} -->
            <component
              :is="item.type"
              :storeId="storeId"
              :key="item.type + '-' + index"
              :class="item.class"
              :Options="isArray(item.Options) ? item.Options : []"
              :placeholder="item.placeholder"
              :modelValue="item.modelValue"
              :defaultValue="item.modelValue"
              :nodeId="node.id"
              :isTree="item.isTree"
              :items="items"
              v-on="
                item.handelDeleceEvent
                  ? {
                      click: () => item.handelDeleceEvent && item.handelDeleceEvent(storeId, priorityIndex, item.index)
                    }
                  : {}
              "
              @update:modelValue="(val) => updateValueFunc(priorityIndex, item.outputkey, item.index, val)"
            >
              <template v-if="item.type == 'Label'">
                {{ item.label }}
              </template>
            </component>
          </div>
        </div>
        <Button class="mt-2" @click.stop="handleClickAddBtn"
          ><plus-icon class="h-6 w-5 cursor-pointer text-primary" />新增</Button
        >
      </div>
    </collapsible-content>
  </Collapsible>
  <Handle type="source" :position="Position.Right" :id="'-ifelse-' + priorityIndex" class="rightPosition" />
</template>

<script lang="ts" setup>
import {
  defineComponent,
  watch,
  ref,
  toRaw,
  reactive,
  onMounted,
  watchEffect,
  isProxy,
  isRef,
  toRefs,
  unref,
  computed
} from 'vue'
import { Handle, Position } from '@vue-flow/core'
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible'
import { ChevronsUpDownIcon, ChevronDown, ChevronUp, PlusIcon, AlertCircleIcon, MinusCircleIcon } from 'lucide-vue-next'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { useVueFlow, useNode } from '@vue-flow/core'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
  SelectItemText
} from '@/components/ui/select'
import storeMap from '@/pina/index'
import SelectComponent from '@/components/vue-flow/nodes/selectComponent.vue'
import {
  IFormItemTypes,
  IOutputItem,
  Branch,
  Condition,
  IEdge,
  ReferenceOption
} from '@/components/vue-flow/nodes/types/form-types.ts'
import { useIfDynamicCom } from '@/lib/useDynamicComponent'
// import { useUpdateNodeData } from '@/lib/updateNodeData'
import { IfNodeRoot } from '@/components/vue-flow/nodes/types/form-types'
import { cloneDeep, indexOf, isArray } from 'lodash'
import { findConnectedNodes } from '@/lib/utils'
defineOptions({
  components: {
    Label,
    Input,
    SelectComponent,
    Textarea,
    ChevronsUpDownIcon,
    ChevronDown,
    ChevronUp,
    PlusIcon,
    AlertCircleIcon,
    MinusCircleIcon
  }
})
const props = defineProps([
  'DLSData' as any,
  'storeId',
  'ItemInfo',
  'properties',
  'description',
  'title',
  'priority',
  'priorityIndex',
  'labels',
  'id'
])
const { getEdges, getNodes, edges } = useVueFlow()
const node = useNode()
let referenceOptions = ref([])

const IfStore = storeMap.useIfStore()
let DLSData: IfNodeRoot = IfStore.nodes.find((item: any) => item.id == node.id)
const { labels, title, description, properties, ItemInfo, priorityIndex, storeId, id } = props
const emit = defineEmits(['onClickAddBtn', 'deleteBranchs'])
const isOpen = ref(true)
let rawOutput
let isTree = ref(false)
let items = ref<any[]>([])
let branchList = ref<any>()
type Option = {
  groupName: string
  options: {
    label: string
    value: string
    id?: string
  }[]
}
const { conditions } = ItemInfo
const getDynamicComponent = (branchsItem: Branch) => {
  branchList.value = branchsItem.conditions && [
    ...branchsItem.conditions.map((el, index) => dynamicComponent(el, index)).flat()
  ]
}
const getIndex = computed(() => {
  return storeMap.useIfStore().getBranchIndex(id, node.id)
})
//渲染form表单
const dynamicComponent = (item: Condition, index: number) => {
  return useIfDynamicCom(item, index, referenceOptions, ItemInfo.conditions.length, node.id)
}

watch(
  ItemInfo,
  (newValue, oldVlaue) => {
    getDynamicComponent(newValue)
  },
  {
    deep: true
  }
)

onMounted(() => {
  handleQueryPrevNodeOutput(true, ItemInfo)
  getDynamicComponent(ItemInfo)
})
const handleClickAddBtn = () => {
  emit('onClickAddBtn', priorityIndex)
}
const handleRemoveFormDataItem = () => {
  // storeMap[storeId].removeItem(priorityIndex)
  console.log(id,'id----------------------')
  emit('deleteBranchs', id)
}

const getConnectedEdgeIds = () => {
  // 获取当前节点链接的所有边
  const connectedEdges = node.connectedEdges?.value || []

  // 提取每条边的 ID
  const edgeIds = connectedEdges.map((edge) => edge.id)
  console.log('连接到当前节点的边的ID: ', edgeIds)
  return edgeIds
}
const vueFlow = useVueFlow()

const handleQueryPrevNodeOutput = (flag, ItemInfo) => {
  const defaultValue = ItemInfo.conditions[0].left.value
  if (flag) {
    const connectedNodes = [...findConnectedNodes(node.id, getEdges.value, getNodes.value)]
    let selectObj = {}
    connectedNodes.map((item) => {
      if (item.data?.output) {
        const istree = item.data.output.some((item: any) => Array.isArray(item.children) && item.children.length > 0)
        const SelectOption = {
          groupName: item.data.title,
          Options: istree
            ? item.data.output
            : item.data.output.map((el: any) => {
                return {
                  label: el.name,
                  value: el.name
                  // ...(defaultValue?{label:defaultValue,value:defaultValue}:{})
                }
              })
        }
        selectObj[item.data.title] = SelectOption
      }
    })
    storeMap.useOptionsStore().addReferenceOption(selectObj)
    const OptionsStore = storeMap.useOptionsStore()
    const options = OptionsStore.referenceObject

    referenceOptions.value = { ...options }
    const nodeId = node.id
    const linkedNodeId = edges.value
      .filter((edge) => edge.source === nodeId || edge.target === nodeId)
      .find((edge) => (edge.source === nodeId ? edge.target : edge.source))?.source
    linkedNodeId && storeMap[storeId]().updateRef(linkedNodeId)
  }
}

type Itarget = {
  [key: string]: boolean
}

watchEffect(() => {
  if (node.connectedEdges && node.connectedEdges.value.length > 0) {
    const nodeId = node.id
    const edges = vueFlow.edges.value

    const incomingEdges: any = edges.find((edge) => edge.target === nodeId) || {}
    const outgoingEdges: any = edges.find((edge) => edge.source === nodeId) || {}
    const { id: leftTransition, source: leftRef } = incomingEdges
    const { id: rightTransition, target: rightRef } = outgoingEdges

    // const filteredEdges = node.connectedEdges.value.filter((item: IEdge) => item.target === node.id)
    // filteredEdges.map((edge: IEdge) =>{
    //   const sourceNode:any = findNode(edge.source)
    //   const sourceid = sourceNode?.id;
    //   // referenceOptions.value = output?.map((item:IOutputItem)=>({
    //   //   label:item.name,
    //   //   value:item.name,
    //   //   id,
    //   // }))
    //   console.log(findNode(edge.source),findNode(edge.target),'=====================')
    // })
    edges.map((item) => {
      const flag = item.id.includes('-else-')
      let type = 'if'
      if (flag) {
        type = 'else'
      }
      IfStore.setTransition({
        leftRef: item.source,
        leftTransition,
        rightRef: item.target,
        rightTransition: item.id,
        id: node.id,
        type
      })
    })

    // if(node.node.data){
    //   node.node.data = {
    //   //给node节点添加到json当中
    //     ...node.node.data,
    //     id: IfStore.template.id,
    //     type: IfStore.template.type,
    //     ...IfStore.template.data
    //   }
    // }
  }
})
const updateValueFunc = (index: number, key = '', conditionsIndex: number, value: string) => {
  // console.log(index, key, conditionsIndex, value, node.id,'----------')
  IfStore.updateInputValue(index, key, conditionsIndex, value, node.id) //同步数据
  // if (storeId !== 'useIfStore') {
  //   useUpdateNodeData(
  //     node,
  //     storeMap[storeId]().template.id,
  //     storeMap[storeId]().template.type,
  //     storeMap[storeId]().template.data
  //   )
  // }
}
</script>

<style lang="scss">
.if-left-bottom-line {
  position: relative;
  height: 100%;
  flex-grow: 1;
  overflow: hidden;
  & > .line {
    position: absolute;
    left: 20%;
    display: block;
    content: '';
    width: 24px;
    height: 100%;
    border-left: 1px solid #38374399;
    border-bottom: 1px solid #38374399;
    //border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
  }
}
.if-left-top-line {
  position: relative;
  height: 100%;
  flex-grow: 1;
  overflow: hidden;
  //top: -10px;
  & > .line {
    position: absolute;
    display: block;
    left: 20%;
    content: '';
    width: 24px;
    height: 100%;
    border-left: 1px solid #38374399;
    border-top: 1px solid #38374399;
    border-top-left-radius: 10px;
    //border-bottom-left-radius: 10px;
  }
}
.andStyle\! {
  padding: 0 !important;
  border: none !important;
  background: none !important;
  outline: none !important;
  box-shadow: none !important;
}
.rightPosition {
  bottom: 0 !important;
}
.ifNodeStyle {
  label {
    &:first-of-type {
      width: 100px;
    }
    &:nth-of-type(2) {
      width: 100px;
    }
    &:last-of-type {
      width: 180px;
    }
  }
}
.w-130 {
  width: 123px;
}
</style>
